import React, { Fragment, useEffect, useState } from 'react'
import { Avatar, Col, Form, List, message, Pagination, Row } from "antd";
import { addArticle, getArticleList } from "../api/article";
import { Link, useNavigate } from "react-router-dom";
import {
    Button,
    Cascader,
    DatePicker,
    Input,
    InputNumber,
    Radio,
    Select,
    Switch,
    TreeSelect,
} from 'antd';

//富文本编辑器
import ReactQuill from "react-quill";
import BackGround from "../components/BackGround";
import '../components/css/message.css'
import '../components/css/blog-info.css'
import TinyMCEEditor from '../components/TinyMCEEditor';


// 博客列表
export function BlogInfo () {

    //获取文章列表
    const [articleList, setArticleList] = useState([])
    const [pageNum, setPageNum] = useState(1)
    const [total, setTotal] = useState(0)
    useEffect(() => {
        getArticleList({ pageNum }).then(res => {
            setArticleList([...res.data.rows])
            setTotal(res.data.total)
        })
    }, []);
    useEffect(() => {
        console.log('文章列表更新', articleList)
    }, [articleList])

    const changePage = (page, pageSize) => {
        getArticleList({ pageNum: page }).then(res => {
            setArticleList([...res.data.rows])
            setTotal(res.data.total)
        })
    }
    return (
        <div>
            <h1 className="blogsList-title">
                All blogs
            </h1>
            <div className="p-6">
                <Row>
                    {/*左边的栏目*/}
                    <Col span={6}>
                    </Col>
                    <Col span={12}>
                        <List
                            itemLayout="horizontal"
                            dataSource={articleList}
                            renderItem={(item, index) => (
                                <List.Item>
                                    <List.Item.Meta
                                        avatar={<Avatar
                                            src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
                                        title={<Link
                                            to={'/blog/content/' + item.articleId}>{item.articleTitle}</Link>}
                                        description={`${item.articleAuthor}, 在${item.articleDate}发表`}
                                    />
                                    <div>点赞数:</div>
                                    <div>{item.articleLikes}</div>
                                </List.Item>
                            )}
                        />
                        <Row justify={"center"}>
                            <Col span={12}>
                                <Pagination defaultCurrent={pageNum} total={total} onChange={changePage} />;
                            </Col>
                        </Row>
                    </Col>
                    {/*右边的栏目*/}
                    <Col span={6}>
                    </Col>
                </Row>
            </div>
        </div>
    )
}


//博客编辑
export function BlogEdit () {

    const navigate = useNavigate()
    const [componentSize, setComponentSize] = useState('default');
    const [value, setValue] = useState("");
    const [title, setTitle] = useState("")
    // 弹出提示
    const [messageApi, contextHolder] = message.useMessage();
    const info = (message, type) => {
        messageApi.open({
            type: type,
            content: message,
        });
    };
    //消息提示框
    const defaultTitle = '请输入文章标题'
    const defaultContent = '请输入文章内容'
    const onFormLayoutChange = ({ size }) => {
        setComponentSize(size);
    };
    const handleInputTitle = (e) => {
        setTitle(e.target.value)
    }
    //保存为文章
    const handleSubmitArticle = () => {
        // 组装文章信息
        const article = {
            articleTitle: title,
            articleContent: value,
        }
        // 添加文章
        addArticle(article).then(res => {
            if (res.data.code === 200) {
                info('文章添加成功~', 'success')
                setTimeout(() => {
                    navigate('/blog')
                }, 500)
            } else {
                info('添加文章失败!', 'error')
            }
        })
    }
    //保存为草稿
    const handleSubmitPaper = () => {

    }
    // 富文本的内容
    useEffect(() => {
        // console.log(value)
    }, [value]);
    useEffect(() => {
        if (title.length >= 15) {
            alert("标题过长!")
            setTitle("")
        }
    }, [title])


    return <Fragment>
        <div className="mt-6">
            {contextHolder}
            <Row justify={"center"}>
                <Col>
                    <Row>
                        <Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=1" />
                        <div className="message-box left">
                            <p>{title}</p>
                        </div>
                    </Row>
                </Col>
                <Col span={12}>
                    <Form
                        labelCol={{
                            span: 10,
                        }}
                        wrapperCol={{
                            span: 14,
                        }}
                        layout="horizontal"
                        initialValues={{
                            size: componentSize,
                        }}
                        onValuesChange={onFormLayoutChange}
                        size={componentSize}
                        style={{
                            maxWidth: 600,
                        }}
                    >
                        <Form.Item label="文章标题">
                            <Input value={title} onChange={(e) => handleInputTitle(e)} />
                        </Form.Item>
                        <Form.Item label="文章内容">
                            {/* 使用 TinyMCE 编辑器 */}
                            <TinyMCEEditor value={value} onChange={(newValue) => setValue(newValue)} />
                        </Form.Item>
                        <Form.Item label="输入文章分类">
                            <Input />
                        </Form.Item>
                        <Form.Item label="操作">
                            <Row gutter={20}>
                                <Col span={6}>
                                    <Button type="primary" onClick={handleSubmitArticle}>发布文章</Button>
                                </Col>
                                <Col span={6}>
                                    <Button type="default" onClick={handleSubmitPaper}>保存为草稿</Button>
                                </Col>
                            </Row>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
            <Row justify={"center"}>
                <Col span={12}>
                    <Row>
                        {title === null || title === '' ?
                            <h1 className="text-slate-300">{defaultTitle}</h1> :
                            <h1>{title}</h1>}
                    </Row>
                    <Row>
                        <Col span={24}>
                            <BackGround>
                                <div style={{ height: '500px', width: '100%', lineHeight: '30px' }}>
                                    {value === null || value === '' ?
                                        <span className="text-slate-500">{defaultContent}</span> :
                                        parseHTMLToReact(value)
                                    }
                                </div>
                            </BackGround>
                        </Col>
                    </Row>
                </Col>
            </Row>
        </div>
    </Fragment >
}

// 将HTML字符串转换为React元素
export function parseHTMLToReact (htmlString) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlString, 'text/html');
    return Array.from(doc.body.childNodes).map((node, index) =>
        convertDomNodeToReact(node, index)
    );
}

export function convertDomNodeToReact (node, index) {
    //处理<br>
    if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR') {
        return <br key={index} />;
    }
    if (node.nodeType === Node.TEXT_NODE) {
        return node.textContent;
    }

    if (node.nodeType !== Node.ELEMENT_NODE) {
        return null;
    }

    const nodeName = node.nodeName.toLowerCase();
    const children = Array.from(node.childNodes).map((childNode, index) =>
        convertDomNodeToReact(childNode)
    );
    return React.createElement(nodeName, { key: nodeName + index }, children);

}